package cn.springmvc.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.springmvc.model.ResultBaseBean;
import cn.springmvc.model.entity.UserBean;
import cn.springmvc.service.IFileUploadService;
import cn.springmvc.util.Constants;
import cn.springmvc.util.SessionManager;



@Controller
public class FileUploadController {
	private static final Logger logger = Logger.getLogger(FileUploadController.class);
	private final String imageRoot = Constants.WORKING_IMAGRE_ROOT;
	
		//通过Spring的autowired注解获取spring默认配置的request
		@Autowired
		private HttpServletRequest request;
		
		@Autowired
		private IFileUploadService fileUploadService;

		@RequestMapping("/uploadform")
	    public String uploadForm(){
	        return "upload";
	    }
				
		
		/***
		 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
		 * 
		 * @param file
		 * @return
		 */
		@RequestMapping(value="/fileUpload", method=RequestMethod.POST)
		public @ResponseBody ResultBaseBean<String> fileUpload(@RequestParam("file") MultipartFile file,@RequestParam("sessionId") String sessionId) {
			ResultBaseBean<String> resultBaseBean = new ResultBaseBean<String>();
			
			SessionManager sessionManager = SessionManager.getInstance();
			HttpSession httpSession = sessionManager.getSessionById(sessionId);
			
			if(httpSession != null){
				UserBean userBean = (UserBean) httpSession.getAttribute("userBean");	
				logger.info("用户 " + userBean.getUserId()+ " - " + userBean.getUserName() + " 开始上传文件 " + file.getOriginalFilename());
				resultBaseBean = fileUploadService.fileUpload(file, userBean, imageRoot);
			}else{
				resultBaseBean.setSuccess(false);
				resultBaseBean.setMessage("请先登录");
			}
			
			
			return resultBaseBean;
		}

		/***
		 * 读取上传文件中得所有文件并返回
		 * 
		 * @return
		 */
		@RequestMapping("/list")
		public String list() {
			
			File uploadDest = new File(imageRoot);
			String[] fileNames = uploadDest.list();
			for (int i = 0; i < fileNames.length; i++) {
				//打印出文件名
				System.out.println(fileNames[i]);
			}
			return "upload";
		}
		

}
